#include "stdafx.h"
#include "DNSHooks.h"


#ifdef _MANAGED
#pragma managed(push, off)
#endif
BOOL APIENTRY DllMain(HMODULE hModule,DWORD  ul_reason_for_call,LPVOID lpReserved)
{
	switch (ul_reason_for_call)
	{
		case DLL_PROCESS_ATTACH:
			dbg1(L"DNSHook Pattach");
			break;
		case DLL_THREAD_ATTACH:
			dbg1(L"DNSHook Tattach");
			break;
		case DLL_THREAD_DETACH:
			dbg1(L"DNSHook Tdetach");
			break;
		case DLL_PROCESS_DETACH:
			dbg1(L"DNSHook Pdetach");
			break;
	}
    return TRUE;
}
#ifdef _MANAGED
#pragma managed(pop)
#endif

DNSSHUTDOWNHOOK_API bool InitDNSHooks(HWND ownerWindow)
{
    HOOKPROC hkprcSysMsg=NULL; 
    static HINSTANCE hinstDLL; 
    static HHOOK hhookSysMsg; 


    HANDLE hMapFile = CreateFileMapping(
                 INVALID_HANDLE_VALUE,    // use paging file
                 NULL,                    // default security 
                 PAGE_READWRITE,          // read/write access
                 0,                       // max. object size 
                 BUF_SIZE,                // buffer size  
                 szMapFileName);                 // name of mapping object
 
	if (hMapFile == NULL || hMapFile == INVALID_HANDLE_VALUE) 
	{ 
		dbg(L"hook::HookDLL() Could not create file mapping object (%d).\n", GetLastError());
		return false;
	}
	LPTSTR pBuf = (LPTSTR) MapViewOfFile(hMapFile,   // handle to mapping object
                        FILE_MAP_ALL_ACCESS, // read/write permission
                        0,                   
                        0,                   
                        BUF_SIZE);    

    
    hinstDLL = LoadLibrary(L"HookProc.dll"); 
	if (!hinstDLL)
	{
		dbg(L"hook::HookDLL() Could not load DLL (%x) ", GetLastError()); 
		return false;
	}
    hkprcSysMsg = (HOOKPROC)GetProcAddress(hinstDLL, "HookProc"); 
    if(!hkprcSysMsg)
	{
		OutputDebugString(L"hook::HookDLL() Could not find MessageProc address");
		return false;
	}
	
    hhookSysMsg = SetWindowsHookEx(WH_CBT,hkprcSysMsg,hinstDLL,0);
	if (!hhookSysMsg)
	{
		dbg(L"hook::HookDLL() Couldn't set hook (%d).\n", GetLastError());
		return false;
	}
	*(HHOOK *)pBuf = hhookSysMsg;

	pBuf++;
	*(HWND *)pBuf = ownerWindow;
	return true;

}
